﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using TinyCms.Core;
using TinyCms.Core.ExtendMethod;
using TinyCms.Core.Repositories;

namespace TinyCms.Domain.Repositories
{
    public class EntityFrameworkRepository<T> : Repository<T>
        where T :EntityBase
    {
        private readonly IEntityFrameworkRepositoryContext _efContext;

        public EntityFrameworkRepository(IRepositoryContext context)
            : base(context)
        {
            if (context is IEntityFrameworkRepositoryContext)
                _efContext = context as IEntityFrameworkRepositoryContext;
        }



        protected override T DoGetByKey(Guid id)
        {
            return _efContext.Context.Set<T>().FirstOrDefault(x => x.ID == id);
        }

        protected override IEnumerable<T> DoGetAll(Expression<Func<T, bool>> pre, Expression<Func<T, dynamic>> sort, SortOrder order = SortOrder.Ascending)
        {
            var result = _efContext.Context.Set<T>().Where(pre);
            if(order== SortOrder.Ascending)
            {
                result = result.OrderBy(sort);
            }
            else if(order==SortOrder.Descending)
            {
                result = result.OrderByDescending(sort);
            }
            return result;
        }

        protected override IEnumerable<T> DoGetPageList(int pageIndex, int pagesize, out int count, Expression<Func<T, bool>> pre, Expression<Func<T, dynamic>> sort, SortOrder order = SortOrder.Ascending)
        {
            return DoGetAll(pre, sort, order).ToPageList(pageIndex, pagesize, out count);
        }

        protected override void DoAdd(List<T> entities)
        {
            foreach (var entity in entities)
            {
                _efContext.RegisterNew(entity);
            }
        }

        protected override void DoUpdate(List<T> entities)
        {
            foreach (var entity in entities)
            {
                _efContext.RegisterModified(entity);
            }
        }

        protected override void DoDelete(List<T> entities)
        {
            foreach (var entity in entities)
            {
                _efContext.RegisterDeleted(entity);
            }
        }

        protected override int DoExecuteCommand(string command)
        {
            return _efContext.Context.Database.ExecuteSqlCommand(command);
        }

        protected override IEnumerable<T> DoExecuteQuery(string command)
        {
            return _efContext.Context.Database.SqlQuery<T>(command);
        }
    }
}
